# Encoding settings
chcp 65001 > $null
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = $OutputEncoding
[Console]::InputEncoding = $OutputEncoding

# Check changes
$changes = git status --porcelain
if ($changes) {
    Write-Host "There are uncommitted changes, processing..." -ForegroundColor Cyan
    git add .
    
    # Get commit message
    $commitMsg = $null
    while ([string]::IsNullOrWhiteSpace($commitMsg)) {
        $commitMsg = Read-Host -Prompt "Please enter commit message"
        if ([string]::IsNullOrWhiteSpace($commitMsg)) {
            Write-Host "Commit message cannot be empty!" -ForegroundColor Red
        }
    }
    git commit -m $commitMsg
}

# Pull remote code
Write-Host "Pulling latest code from remote..." -ForegroundColor Cyan
git pull --rebase origin master
if ($LASTEXITCODE -ne 0) {
    Write-Host "Pull failed, there may be conflicts" -ForegroundColor Red
    exit 1
}

# Push code
Write-Host "Pushing code to remote..." -ForegroundColor Cyan
git push origin master
if ($LASTEXITCODE -eq 0) {
    Write-Host "Push successful!" -ForegroundColor Green
} else {
    Write-Host "Push failed, please check network or permissions" -ForegroundColor Red
    exit 1
}
